package top.qingyunge.autumn.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.web.method.HandlerMethod;
import top.qingyunge.autumn.annotation.IgnoreToken;
import top.qingyunge.autumn.util.JwtUtil;
import top.qingyunge.autumn.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.Map;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull Object handler) {

            // 判断controller方法
        if(handler instanceof HandlerMethod handlerMethod){
            // 没有controller处理方法
            Method method = handlerMethod.getMethod();//获得被拦截的方法对象
            IgnoreToken ignoreToken = method.getAnnotation(IgnoreToken.class);//获得方法上的注解
            if (ignoreToken != null) {
                return true;
            }
            // 获取token
            String token = request.getHeader("Authorization");
            // 验证token
            try {
                Map<String, Object> claims = JwtUtil.parseToken(token);
                // 存储业务信息到线程变量
                ThreadLocalUtil.set(claims);
                // 放行拦截
                return true;
            } catch (Exception e) {
                // 登录状态失效或未登录，http响应状态码为401
                response.setStatus(401);
                // 拦截请求
                return false;
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull Object handler, Exception ex) {
        // 清除ThreadLocal业务数据
        ThreadLocalUtil.remove();
    }
}

